#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
#include <wait.h>
using namespace srd;

pthread_mutex_t mutex;

void* another(void* arg) {
    cout << "in child thread, lock the mutex" << endl;
    pthread_mutex_lock(&mutex);
    sleep(5);
    pthread_mutex_unlock(&mutex);
}

int main() {
    pthread_mutex_init(&mutex, nullptr);
    pthread_t id ;
    pthread_create(&id, nullptr, another, nullptr);
    sleep(1);
    int pid = fork();
    if(pid < 0){
        pthread_join(id, nullptr);
        pthread_mutex_destroy(&mutex);
        return 1;
    }
    else if(pid == 0) {
        cout << "I am in the child, want to get the lock" << endl;
        pthread_mutex_lock(&mutex);
        cout << "I can not run to here, oop..." << endl;
        pthread_mutex_unlock(&mutex);
        exit(0);
    }
    else {
        wait(nullptr);
    }
    pthread_join(id, nullptr);
    pthread_mutex_destroy(&mutex);
    return 0;
}